﻿/**
 * DeltaTime
 *
 * @author		Duarte Peixinho
 * @version		1.0
 */

package com.duartepeixinho.deltaTime 
{
	public class DeltaTime
	{
		
		private var DELTA_SCALE:Number;
		private var _lastTime:Number;
		private var _currentTime:Number;
		private var _expectedFps:Number;
		private var _expTimeMillisecs:Number;
		
		/**
		 * Delta Time
		 * @param	expectedFps		Number		Set the delta time value
		 */
		public function DeltaTime(expectedFps:Number) 
		{
			this.delta_time = expectedFps;					//sets the expected fps using the setter method
		}
		
		/**
		 * Calculation of the Delta Time
		 * @return					Number		Get the delta scale
		 */
		public function onRenderTick():Number {
			return calculateDeltaTime();					//returns the delta scale
		}
		
		/**
		 * Calculate Delta Scale
		 * @return					Number		Returns the value of the Delta Scale
		 */
		private function calculateDeltaTime():Number {  
			_currentTime = new Date().getTime();			//gets the current time
            var timeElapsed:int = _currentTime-_lastTime;	//gets the time since the last time		
            DELTA_SCALE = timeElapsed / _expTimeMillisecs;	//calculates the delta scale
            _lastTime = _currentTime;						//saves the current time as last time
			return DELTA_SCALE;								//returns delta scale
        }  
		
		/* 
		 * -----------------------------------------------------------------------------------------------------------------
		 *	Getter and Setter methods
		 * -----------------------------------------------------------------------------------------------------------------
		 */
		
		/**
		 * delta time getter
		 * @return					Number		Get the expected fps value
		 */
		public function get delta_time():Number {
			return _expectedFps;							//returns the delta scale
		}
		
		/**
		 * delta time setter
		 * @param	expectedFps		Number		Set the expected fps value
		 */
		public function set delta_time(expectedFps:Number):void {			
			_expectedFps = expectedFps; 					//sets the private var expectedFps
			_expTimeMillisecs = 1000 / _expectedFps; 		//calculates the expectedtime in milliseconds
			_lastTime = new Date().getTime();				//saves the last moment
		}
		
	}
	
}